package com.bytedance.social.service.impl;

import com.bytedance.social.common.JwtUtil;
import com.bytedance.social.common.StatusCode;
import com.bytedance.social.mapper.MessageMapper;
import com.bytedance.social.mapper.RelationMapper;
import com.bytedance.social.mapper.SocailMapper;
import com.bytedance.social.pojo.FriendUser;
import com.bytedance.social.pojo.Message;
import com.bytedance.social.pojo.Relation;
import com.bytedance.social.pojo.User;
import com.bytedance.social.properties.ZhiPuAiProperties;
import com.bytedance.social.request.FollowListRequest;
import com.bytedance.social.request.FollowerListRequest;
import com.bytedance.social.request.FriendListRequest;
import com.bytedance.social.request.RelationActionRequest;
import com.bytedance.social.respones.FollowListResponse;
import com.bytedance.social.respones.FollowerListResponse;
import com.bytedance.social.respones.FriendListResponse;
import com.bytedance.social.respones.RelationActionResponse;
import com.bytedance.social.service.RelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class RelationServiceImpl implements RelationService {


    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private SocailMapper socailMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private ZhiPuAiProperties puAiProperties;

    /**
     * 对用户登录的用户进行关注或者取消关注
     * request
     * required string token = 1; // 用户鉴权token
     * required int64 to_user_id = 2; // 对方用户id
     * required int32 action_type = 3; // 1-关注，2-取消关注
     * <p>
     * response
     * required int32 status_code = 1; // 状态码，0-成功，其他值-失败
     * optional string status_msg = 2; // 返回状态描述
     *
     * @return
     */
    @Override
    @Transactional
    public RelationActionResponse relationAction(RelationActionRequest relationActionRequest) {

        //从token中取出currentUserId
        Long currentUserId = JwtUtil.parseToken(relationActionRequest.getToken());
        Long toUserId = relationActionRequest.getTo_user_id();
        RelationActionResponse relationActionResponse = new RelationActionResponse();
        if (currentUserId == toUserId) {
            //直接return
            relationActionResponse.setStatus_code(StatusCode.STATUS_FAIL);
            relationActionResponse.setStatus_msg("自己不能关注自己嗷！");
            return relationActionResponse;
        }

        Integer actionType = relationActionRequest.getAction_type();
        Relation relation = new Relation();
        relation.setUser_id(currentUserId);
        relation.setTo_user_id(toUserId);
        //查currentUser和toUser回来
        User currentUser = socailMapper.selectUserById(currentUserId);
        User toUser = socailMapper.selectUserById(toUserId);

        if (actionType == 1) {
            //校验是否关注
            Relation relation1 = relationMapper.selectIsFollow(currentUserId, toUserId);
            if (relation1 != null) {
                //说明已关注
                relationActionResponse.setStatus_msg("你已经关注了嗷，下拉刷新查看！");
                relationActionResponse.setStatus_code(StatusCode.STATUS_FAIL);
                return relationActionResponse;
            }
            //关注，向关系表中插入关系,以及修改user表中follower_count粉丝总数和自身的user的follow_count关注总数
            relationMapper.updateUserFollowCount(currentUser.getId(), currentUser.getFollow_count() + 1);
            relationMapper.updateUserFollowerCount(toUserId, toUser.getFollower_count() + 1);
            relationMapper.insertRelation(relation);
            relationActionResponse.setStatus_code(StatusCode.STATUS_OK);
            relationActionResponse.setStatus_msg("关注成功嗷！");
            return relationActionResponse;
        } else if (actionType == 2) {
            //取消关注
            if (toUserId == puAiProperties.getAIId()) {
                //直接return
                relationActionResponse.setStatus_code(StatusCode.STATUS_FAIL);
                relationActionResponse.setStatus_msg("不能取消关注AI嗷！");
                return relationActionResponse;
            }
            //向关系表中插入关系,以及修改user表中follower_count粉丝总数和自身的user的follow_count关注总数
            relationMapper.updateUserFollowCount(currentUser.getId(), currentUser.getFollow_count() - 1);
            relationMapper.updateUserFollowerCount(toUserId, toUser.getFollower_count() - 1);
            relationMapper.deleteRelation(relation);
            relationActionResponse.setStatus_code(StatusCode.STATUS_OK);
            relationActionResponse.setStatus_msg("取消关注成功嗷！");
            return relationActionResponse;
        }
        return relationActionResponse;
    }

    /**
     * /douyin/relatioin/follow/list/ - 用户关注列表
     * 登录用户关注的所有用户列表。
     * request
     * required int64 user_id = 1; // 用户id
     * required string token = 2; // 用户鉴权token
     * <p>
     * response
     * required int32 status_code = 1; // 状态码，0-成功，其他值-失败
     * optional string status_msg = 2; // 返回状态描述
     * repeated User user_list = 3; // 用户信息列表
     *
     * @param followListRequest
     * @return
     */
    @Override
    public FollowListResponse getUserFollowList(FollowListRequest followListRequest) {
        FollowListResponse followListResponse = new FollowListResponse();
        Long userId = followListRequest.getUser_id();
        List<Relation> relationList = relationMapper.selectFollows(userId);
        List<User> users = new ArrayList<>();
        for (Relation relation : relationList) {
            Long toUserId = relation.getTo_user_id();
            //查询user表
            User user = socailMapper.selectUserById(toUserId);
            //查询关系表，是否已经关注
            /**
             * 显然自己对自己不能关注，做一下校验。
             */
            //设置当前user的Is_follow
            Relation relation1 = relationMapper.selectIsFollow(userId, toUserId);
            if (relation1 == null) {
                //说明没关注
                user.setIs_follow(false);
            } else {
                user.setIs_follow(true);
            }
            users.add(user);
        }
        if (users.size() == 0 || users == null) {
            followListResponse.setStatus_code(StatusCode.STATUS_FAIL);
            followListResponse.setStatus_msg("当前用户没有关注嗷！");
            return followListResponse;
        }
        followListResponse.setUser_list(users);
        followListResponse.setStatus_code(StatusCode.STATUS_OK);
        followListResponse.setStatus_msg("获取列表成功");
        return followListResponse;
    }

    /**
     * 所有关注登录用户的粉丝列表。
     * required int32 status_code = 1; // 状态码，0-成功，其他值-失败
     * optional string status_msg = 2; // 返回状态描述
     * repeated User user_list = 3; // 用户列表
     *
     * @param followerListRequest
     * @return
     */
    @Override
    public FollowerListResponse getUserFollowerList(FollowerListRequest followerListRequest) {
        Long currentUserId = followerListRequest.getUser_id();
        List<Relation> relationList = relationMapper.selectFollowers(currentUserId);
        List<User> users = new ArrayList<>();
        for (Relation relation : relationList) {
            Long toUserId = relation.getUser_id();
            User user = socailMapper.selectUserById(toUserId);
            /**
             * 显然自己对自己不是粉丝，做一下校验。
             */
            //查看是否已经关注
            Relation relation1 = relationMapper.selectIsFollow(currentUserId, toUserId);
            if (relation1 == null) {
                //未关注
                user.setIs_follow(false);
            } else {
                //已关注
                user.setIs_follow(true);
            }
            users.add(user);
        }
        FollowerListResponse followerListResponse = new FollowerListResponse();
        if (users.size() == 0 || users == null) {
            followerListResponse.setStatus_code(StatusCode.STATUS_FAIL);
            followerListResponse.setStatus_msg("当前用户没有粉丝嗷！");
            return followerListResponse;
        }
        followerListResponse.setUser_list(users);
        followerListResponse.setStatus_code(StatusCode.STATUS_OK);
        followerListResponse.setStatus_msg("查询粉丝成功！");
        return followerListResponse;
    }

    /**
     * 所有关注登录用户的粉丝列表（好友列表）
     * <p>
     * required int32 status_code = 1; // 状态码，0-成功，其他值-失败
     * optional string status_msg = 2; // 返回状态描述
     * repeated FriendUser user_list = 3; // 用户列表
     *
     * @param friendListRequest
     * @return
     */
    @Override
    public FriendListResponse getUserFriends(FriendListRequest friendListRequest) throws ParseException {
        Long currentUserId = friendListRequest.getUser_id();
        //添加AI好友，判断有无AI好友
        Relation relation1 = relationMapper.selectIsFollow(currentUserId, puAiProperties.getAIId());//当前用户关注AI
        Relation relation2 = relationMapper.selectIsFollow(puAiProperties.getAIId(), currentUserId);//当前AI关注用户
        Relation relation3 = new Relation();
        relation3.setUser_id(currentUserId);
        relation3.setTo_user_id(puAiProperties.getAIId());
        Relation relation4 = new Relation();
        relation4.setUser_id(puAiProperties.getAIId());
        relation4.setTo_user_id(currentUserId);
        if (relation1 == null && relation2 == null) {
            relationMapper.insertRelation(relation3);
            relationMapper.insertRelation(relation4);
        } else if (relation1 == null && relation2 != null) {
            relationMapper.insertRelation(relation3);
        } else if (relation1 != null && relation2 == null) {
            relationMapper.insertRelation(relation4);
        }
        List<Relation> relationList = relationMapper.selectFollowers(currentUserId);
        List<FriendUser> friendUsers = new ArrayList<>();
        for (Relation relation : relationList) {
            //获取粉丝id
            Long userId = relation.getUser_id();
            User user = socailMapper.selectUserById(userId);
            FriendUser friendUser = new FriendUser();
            BeanUtils.copyProperties(user, friendUser);
            Message message = messageMapper.selectMessageByFromAndTo(currentUserId, userId);
            Message message1 = messageMapper.selectMessageByFromAndTo(userId, currentUserId);
            if (message != null && message1 == null) {
                //说明message在前
                friendUser.setMessage(message.getContent());
                friendUser.setMsgType(1L);
            } else if (message1 != null && message == null) {
                //说明message1在前
                friendUser.setMessage(message1.getContent());
                friendUser.setMsgType(0L);
            } else if (message != null && message1 != null) {
                //说明都存在，比较时间
                if (message.getCreate_time() >= message1.getCreate_time()) {
                    friendUser.setMessage(message.getContent());
                    friendUser.setMsgType(1L);
                } else {
                    friendUser.setMessage(message1.getContent());
                    friendUser.setMsgType(0L);
                }
            }
            friendUsers.add(friendUser);
        }
        FriendListResponse friendListResponse = new FriendListResponse();
        //判断一下
        if (friendUsers.size() == 0 || friendUsers == null) {
            friendListResponse.setStatus_code(StatusCode.STATUS_FAIL);
            friendListResponse.setStatus_msg("互关才能成为好友嗷！");
            return friendListResponse;
        }
        friendListResponse.setStatus_code(StatusCode.STATUS_OK);
        friendListResponse.setStatus_msg("获取好友列表成功！");
        friendListResponse.setUser_list(friendUsers);
        return friendListResponse;
    }
}
